<template>
  <div>
    <!-- 面包屑区域 -->
    <Breadcrumb></Breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showEditOrAddDialog()"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index == 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item, index) in scope.row.children"
              :key="item.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">
                  {{ item.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="['bdbottom', idx == 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(it, idx) in item.children"
                  :key="it.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, it.id)"
                    >
                      {{ it.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="e in it.children"
                      :key="e.id"
                      closable
                      @close="removeRightById(scope.row, e.id)"
                    >
                      {{ e.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditOrAddDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeScopeById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightDialog(scope.row)"
              >分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      @close="defkey = []"
    >
      <!-- 树形组件 -->
      <el-tree
        :data="rightlist"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defkey"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加和修改用户对话框  -->
    <el-dialog
      :title="dialogData[sta].title"
      :visible.sync="userDialogVisible"
      width="50%"
      @close="reset"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrModifyUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Breadcrumb from "../Breadcrumb";
import { getRolesData,deleteRight,getRightData,allotRight,addRoles,editRoles,deleteRoles} from '@/request/rolesAPI'
export default {
  components: {
    Breadcrumb,
  },
  data() {
    return {
      // 角色列表数据
      rolelist: [],
      // 权限管理对话框开关
      setRightDialogVisible: false,
      // 添加用户对话框开关
      userDialogVisible: false,
      // 获取所有权限管理数据
      rightlist: [],
      //   属性组件参数
      treeProps: {
        label: "authName",
        children: "children",
      },
      //  默认选中权限的ID
      defkey: [],
      // 用户的ID
      roleId: "",
      // 添加用户的数据
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加用户规则验证
      rules: {
        roleName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      compileDialogVisible: false,
      sta: 0,
      modifyId:null,
      dialogData: [
        {
          title: "添加角色",
          msg: "添加用户成功",
          msg1: "添加用户失败",
        },
        {
          title: "修改角色",
          msg: "修改成功",
          msg1: "修改失败",
        },
        
      ],
    };
  },
  created() {
    this.getRoleslist();
  },
  methods: {
    // 点击对话框开关时要做的事情
    showEditOrAddDialog(data) { //e
      if (data) {
        this.sta = 1;
        this.modifyId = data.id
        this.ruleForm.roleName = data.roleName;
        this.ruleForm.roleDesc = data.roleDesc;
      } else {
        this.sta = 0;
        this.ruleForm.roleName = "";
        this.ruleForm.roleDesc = "";
      }
      this.userDialogVisible = true;
    },
    // 关闭对话框移除表单验证效果
    reset() {
      this.$refs.ruleFormRef.clearValidate();
    },
    // 获取数据
    async getRoleslist() {
      let { data: res } = await getRolesData();
      if (res.meta.status !== 200)
        return this.$message.error("获取列表数据失败");
      this.rolelist = res.data;
      // console.log(this.rolelist);
    },
    // 根据id删除权限
    async removeRightById(role, rightId) {
      // 弹框提示
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      let { data: res } = await deleteRight(role.id , rightId);
      if (res.meta.status !== 200) return this.$message.error("删除权限失败！");
      //   this.getRoleslist();
      role.children = res.data;
    },
    // 分配权限 (分配权限对话框开关)
    async showRightDialog(role) {
      // 获取所有权限的数据
      let { data: res } = await getRightData();
      if (res.meta.status !== 200)
        return this.$message.error("获取权限数据失败！");
      // 获取权限数据存到data中
      this.rightlist = res.data;
      //   console.log(this.rightlist);
      // 获取默认选中权限(三级节点)的ID
      this.getkeys(role, this.defkey);
      console.log(this.defkey);
      this.roleId = role.id;
      this.setRightDialogVisible = true;
    },
    // 利用递归获取默认选中权限(三级节点)的ID
    getkeys(node, arr) {
      // 递归终止条件 没有children 就是三级节点了
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getkeys(item, arr));
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idstr = keys.join(",");
      let { data: res } = await allotRight(this.roleId,idstr);
      if (res.meta.status !== 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      this.getRoleslist();
      this.setRightDialogVisible = false;
      console.log(keys);
      console.log(res);
    },
    // 添加和修改用户
    addOrModifyUser() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return;
        if (this.sta === 0) {  //添加 
          let { data: res } = await addRoles(this.ruleForm);
          if (res.meta.status !== 201) return this.$message.error(this.dialogData[this.sta].msg1);
        } else {  //  1 是修改
          let { data: res } = await editRoles(this.modifyId, this.ruleForm);
          if (res.meta.status !== 200) return this.$message.error(this.dialogData[this.sta].msg1);
        }
        this.$message.success(this.dialogData[this.sta].msg);
        this.getRoleslist();
        this.$refs.ruleFormRef.resetFields();
        this.userDialogVisible = false;
      });
    },
    // 删除当前行
    async removeScopeById(rolesId){
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);
      if (confirmResult !== "confirm") return this.$message.info("已取消删除");
      let {data:res} = await deleteRoles(rolesId)
      if (res.meta.status !== 200) return this.$message.error("删除角色失败！");
      this.$message.success("删除角色成功！");
      this.getRoleslist();
    }
  },
};
</script>
<style lang="scss" scoped>
.el-row {
  margin-bottom: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>